package com.patMall.controller;

import com.patMall.entity.UserAddress;
import com.patMall.service.UserAddressService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;

/**
 * @Author 750909637@qq.com
 * @PackageName patMall
 * @Package com.patMall.controller
 * @Date 2024/1/31 12:14
 * @Version 1.0
 */
@Controller
@RequestMapping("address")
public class AddressController {
    @Resource
    private UserAddressService userAddressService;

    @PostMapping("updateAddressIsDefault")
    @ResponseBody
    public String updateAddressIsDefault(UserAddress userAddress){
        System.err.println(userAddress);
        UserAddress isDefault = userAddressService.selectById(userAddress.getUserId(),1);
        isDefault.setIsDefault(0);
        System.err.println("isDefault"+isDefault);
        int count = userAddressService.updateAddress(isDefault);
        System.err.println("count"+count);
        if (count == 1){
            userAddress.setIsDefault(1);
            System.out.println(userAddress);
            int newCount = userAddressService.updateAddress(userAddress);
            System.err.println("newCount"+newCount);
            if (newCount == 1){
                return "success";
            }
        }
        return "fail";
    }

    @PostMapping("addAddress")
    @ResponseBody
    public String addAddress(UserAddress userAddress){
        if (userAddress.getIsDefault() == 1) {
            UserAddress isDefault = userAddressService.selectById(userAddress.getUserId(), 1);
            isDefault.setIsDefault(0);
            System.err.println("isDefault" + isDefault);
            int count = userAddressService.updateAddress(isDefault);
            if (count == 1) {
                int newCount = userAddressService.insert(userAddress);
                if (newCount == 1) {
                    return "success";
                }
            }
        }else {
            int newCount = userAddressService.insert(userAddress);
            if (newCount == 1) {
                return "success";
            }
        }
        return "fail";
    }
}
